<template>
  <n-breadcrumb px-12>
    <template v-for="breadcrumb in breadcrumbs" :key="breadcrumb.key">
      <n-breadcrumb-item>
        <n-dropdown
          v-if="breadcrumb.hasChildren"
          :options="breadcrumb.options"
          @select="dropdownSelect"
        >
          <div f-y-c>
            <component
              v-if="themeStore.header.crumb.showIcon"
              :is="breadcrumb.icon!"
            />
            <span ml-3 line-height-14>
              {{ breadcrumb.label }}
            </span>
          </div>
        </n-dropdown>
        <div v-else f-y-c>
          <component
            v-if="themeStore.header.crumb.showIcon"
            :is="breadcrumb.icon!"
          />
          <span ml-3 line-height-14>{{ breadcrumb.label }}</span>
        </div>
      </n-breadcrumb-item>
    </template>
  </n-breadcrumb>
</template>

<script setup lang="ts">
import { useRouteStore, useThemeStore } from "@/store";
import { type DropdownOption } from "naive-ui";

const route = useRoute();
const router = useRouter();
const routerStore = useRouteStore();
const themeStore = useThemeStore();

const breadcrumbs = computed<App.GlobalBreadcrumb[]>(() => {
  const tmpMenus = ref(routerStore.menus);
  return route.matched.map((routeMch, idx) => {
    let menuMapper = tmpMenus.value?.find((menu) => menu.key === routeMch.name);
    //@ts-ignore
    tmpMenus.value = menuMapper?.children || [];
    const options = menu2Dropdown(
      menuMapper?.children || [],
      route.matched[idx + 1]?.name as string
    );
    return {
      options,
      hasChildren: !!options && !!options.length,
      icon: menuMapper?.icon,
      label: menuMapper?.label,
    } as App.GlobalBreadcrumb;
  });
});

const menu2Dropdown = (
  menus?: App.GlobalMenuOption[],
  nextKey?: string
): DropdownOption[] | undefined => {
  if (!menus || !menus.length) return;

  return menus
    .filter((menu) => !nextKey || menu.key != nextKey)
    .map((menu) => {
      return {
        label: menu.label as string,
        key: menu.key as string,
        icon: menu.icon,
        children: menu2Dropdown(menu.children),
      } as DropdownOption;
    });
};

const dropdownSelect = (key: string) => {
  router.push({ name: key });
};
</script>

<style scoped></style>
